package com.ruoyi.flowable.listener.asset;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.equ.domain.EquStockin;
import com.ruoyi.flowable.service.IWorkOrderAssetRelService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 验收2、到货信息、包装核查结果、附件链接
 * 更新工单状态
 */
@Slf4j
@Component("assetListener_2")
public class AssetListener_2 implements ExecutionListener {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private static final IWorkOrderAssetRelService workOrderAssetRelService = SpringUtils.getBean(IWorkOrderAssetRelService.class);

    @Override
    public void notify(DelegateExecution execution) {
        try {
            //到货信息:运输单位+运输单号+实际到货日期
            String transportUnit = execution.getVariable("transportUnit", String.class);
            String transportNo = execution.getVariable("transportNo", String.class);
            String arrivalDate = execution.getVariable("arrivalDate", String.class);
            HashMap<String, Object> arrivalInfoMap = new HashMap<>();
            arrivalInfoMap.put("运输单位", transportUnit);
            arrivalInfoMap.put("运输单号", transportNo);
            arrivalInfoMap.put("实际到货日期", arrivalDate);
            String arrivalInfo = objectMapper.writeValueAsString(arrivalInfoMap);

            //包装核查结果:包装状态+密封状态+破损描述+核查人+日期
            String packageStatus = execution.getVariable("packageStatus", String.class);
            String sealStatus = execution.getVariable("sealStatus", String.class);
            List<String> brokenPhotos = getFileList(execution, "brokenPhotos");
            String exceptionDesc = execution.getVariable("exceptionDesc", String.class);
            String nickName = SecurityUtils.getLoginUser().getUser().getNickName();
            String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            HashMap<String, Object> packageCheckMap = new HashMap<>();
            packageCheckMap.put("包装状态", packageStatus);
            packageCheckMap.put("密封状态", sealStatus);
            packageCheckMap.put("异常处理", brokenPhotos);
            packageCheckMap.put("破损描述", exceptionDesc.equals("") ? "无破损" : exceptionDesc);
            packageCheckMap.put("核查人", nickName);
            packageCheckMap.put("日期", date);
            String packageCheck = objectMapper.writeValueAsString(packageCheckMap);

            //附件链接
            List<String> packages = getFileList(execution, "packageImage");
            List<String> report = getFileList(execution, "checkReport");
            List<String> certificate = getFileList(execution, "certificate");
            //赋值
            Map<String, Object> fileUrlsMap = new HashMap<>();
            fileUrlsMap.put("异常处理", brokenPhotos);
            fileUrlsMap.put("包装照片", packages);
            fileUrlsMap.put("检测报告", report);
            fileUrlsMap.put("产品合格证", certificate);
            String fileUrls = objectMapper.writeValueAsString(fileUrlsMap);

            //审批记录
            String deptName = SecurityUtils.getLoginUser().getUser().getDept().getDeptName();
            List<Map<String, String>> approvalRecordList = new ArrayList<>();
            Map<String, String> record = new HashMap<>();
            record.put("name", nickName);
            record.put("dept", deptName);
            record.put("date", date);
            approvalRecordList.add(record);
            String approvalRecord = objectMapper.writeValueAsString(approvalRecordList);

            //审批信息
            Map<String, Object> approvalInfoMap = new HashMap<>();
            approvalInfoMap.put("到货信息", arrivalInfoMap);
            approvalInfoMap.put("包装核查结果", packageCheckMap);
            approvalInfoMap.put("附件链接", fileUrlsMap);
            approvalInfoMap.put("审批记录", approvalRecordList);
            String approvalInfo = objectMapper.writeValueAsString(approvalInfoMap);

            EquStockin equStockin = new EquStockin();
            equStockin.setArrivalInfo(arrivalInfo);
            equStockin.setPackageCheck(packageCheck);
            equStockin.setFileUrls(fileUrls);
            equStockin.setApprovalRecord(approvalRecord);

            equStockin.setApprovalInfo(approvalInfo);

            execution.setVariable("equStockin", equStockin);

            //更新工单状态(流程实例和资产结合的工单)
            String processInstanceId = execution.getProcessInstanceId();
            workOrderAssetRelService.updateWorkOrderStatus(processInstanceId, "处理中", null);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    //获取符合文件格式 [{url:"xxx"},{url:"xxx"}] -> ["xxx", "xxx"]
    //没有返回[]
    public static List<String> getFileList(DelegateExecution execution, String varName) {
        List<String> files = new ArrayList<>();
        List<Map<String, Object>> list = (List<Map<String, Object>>) execution.getVariable(varName);
        if (list != null && !list.isEmpty()) {
            files = list.stream().map(item -> (String) item.get("url")).collect(Collectors.toList());
        }
        return files;
    }
}
